package com.cain.calendar.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cain.calendar.R;
import com.cain.calendar.adapter.CalendarAdapter;
import com.cain.calendar.adapter.CalendarPagerAdapter;
import com.cain.calendar.bean.Event;
import com.cain.calendar.dao.CalendarDAO;
import com.cain.calendar.tool.*;
import com.cain.calendar.view.EventView;

import java.util.ArrayList;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private TextView monthDateTextView;   //显示月份和时间的textView
    private TextView yearTextView;   //年份
    private TextView diffTextView;   //显示和点击处相差几天的textView
    private RelativeLayout todayButton;   //跳转到本月按钮
    private TextView todayText;   //当日数字
    private LinearLayout panel;   //主面板
    private ViewPager calendarPanel;   //日历面板
    private RelativeLayout eventPanel;   //日历表格面板
    private GridView[] calendarArray;   //日历表格列表
    private CalendarAdapter[] calendarAdapterArray;   //日历适配器列表
    private EventView eventView;   //事件面板
    private TextView noneTextView;   //无事件文字

    private static final int REQUEST_CODE_ADD_EVENT = 100;
    private static final int REQUEST_CODE_SHOW_EVENT = 101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        CalendarDAO.openDatabase();

        setContentView(R.layout.activity_main);
        monthDateTextView = (TextView) findViewById(R.id.main_month_date);
        yearTextView = (TextView) findViewById(R.id.main_year);
        diffTextView = (TextView) findViewById(R.id.main_diff);
        todayButton = (RelativeLayout) findViewById(R.id.main_today);
        todayText = (TextView) findViewById(R.id.main_today_text);
        panel = (LinearLayout) findViewById(R.id.main_panel);
        calendarPanel = (ViewPager) findViewById(R.id.main_calendar_panel);
        eventPanel = (RelativeLayout) findViewById(R.id.main_event_panel);
        eventView = (EventView) findViewById(R.id.main_event_view);
        noneTextView = (TextView) findViewById(R.id.main_none_text_view);

        init();
    }

    private CalendarAdapter.Item lastItem;
    private AdapterView.OnItemClickListener calendarItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            resetLastItem();
            CalendarAdapter.Item item = (CalendarAdapter.Item) view.getTag();
            chooseItem(item);
        }
    };

    /**
     * 重置上一个item
     */
    private void resetLastItem() {
        if (lastItem != null && !MyCalendar.isToday(lastItem.year, lastItem.month, lastItem.day)) {
            lastItem.panel.setBackgroundResource(R.drawable.calendar_item_normal);
        }
    }

    /**
     * 选中item
     * @param item
     */
    private void chooseItem(CalendarAdapter.Item item) {
        if (item.year != 0) {
            if (!MyCalendar.isToday(item.year, item.month, item.day)) {
                item.panel.setBackgroundResource(R.drawable.calendar_item_chosen);
            }
            setChosenDay(item.year, item.month, item.day);
            lastItem = item;
        }
    }

    /**
     * 初始化
     */
    private void init() {
        final Calendar calendar = Calendar.getInstance();
        calendarAdapterArray = new CalendarAdapter[3];
        calendarAdapterArray[0] = new CalendarAdapter(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH));
        calendar.add(Calendar.MONTH, 1);
        calendarAdapterArray[1] = new CalendarAdapter(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH));
        calendar.add(Calendar.MONTH, -2);
        calendarAdapterArray[2] = new CalendarAdapter(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH));

        View[] calendarViews = new View[5];
        calendarArray = new GridView[5];
        for (int i = 0; i < calendarViews.length; ++i) {
            LayoutInflater inflater = this.getLayoutInflater();
            calendarViews[i] = inflater.inflate(R.layout.calendar, null);
            calendarArray[i] = (GridView) calendarViews[i].findViewById(R.id.calendar_view);
            calendarArray[i].setSelector(new ColorDrawable(Color.TRANSPARENT));
            calendarArray[i].setOnItemClickListener(calendarItemClickListener);
        }
        calendarArray[0].setAdapter(calendarAdapterArray[2]);
        calendarArray[1].setAdapter(calendarAdapterArray[0]);
        calendarArray[2].setAdapter(calendarAdapterArray[1]);
        calendarArray[3].setAdapter(calendarAdapterArray[2]);
        calendarArray[4].setAdapter(calendarAdapterArray[0]);
        calendarArray[0].setTag(2);
        calendarArray[1].setTag(0);
        calendarArray[2].setTag(1);
        calendarArray[3].setTag(2);
        calendarArray[4].setTag(0);

        calendarPanel.setAdapter(new CalendarPagerAdapter(this, calendarViews));
        calendarPanel.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            private int lastPosition = -1;   //上一个view的下标
            private int position;   //选择的页面坐标

            @Override
            public void onPageSelected(int position) {
                System.out.println("onPageSelected");
                this.position = position;
                resetLastItem();
                switch (position) {
                    case 0:
                        lastItem = calendarAdapterArray[2].getDefChosenItem();
                        break;

                    case 1:
                        lastItem = calendarAdapterArray[0].getDefChosenItem();
                        break;

                    case 2:
                        lastItem = calendarAdapterArray[1].getDefChosenItem();
                        break;

                    case 3:
                        lastItem = calendarAdapterArray[2].getDefChosenItem();
                        break;

                    case 4:
                        lastItem = calendarAdapterArray[0].getDefChosenItem();
                        break;
                }
                if (lastItem != null) setChosenDay(lastItem.year, lastItem.month, lastItem.day);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                System.out.println("onPageScrollStateChanged");
                switch (state) {
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        System.out.println("SCROLL_STATE_DRAGGING");
                        break;

                    case ViewPager.SCROLL_STATE_IDLE:
                        System.out.println("SCROLL_STATE_IDLE");
                        System.out.println("position:" + position);
                        int index = (Integer) calendarArray[position].getTag();
                        int lastIndex;
                        if (lastPosition != -1)
                            lastIndex = (Integer) calendarArray[lastPosition].getTag();
                        else
                            lastIndex = -1;
                        int[] time;
                        switch (position) {
                            case 0:
                                time = calendarAdapterArray[2].getMonthAhead();
                                calendarAdapterArray[1].setCurrentYear(time[0]);
                                calendarAdapterArray[1].setCurrentMonth(time[1]);
                                calendarAdapterArray[1].notifyDataSetChanged();
                                calendarPanel.setCurrentItem(3, false);
                                break;

                            case 1:
                                if (index == lastIndex) {
                                    time = calendarAdapterArray[0].getMonthNext();
                                    calendarAdapterArray[1].setCurrentYear(time[0]);
                                    calendarAdapterArray[1].setCurrentMonth(time[1]);
                                    calendarAdapterArray[1].notifyDataSetChanged();
                                } else {
                                    time = calendarAdapterArray[0].getMonthAhead();
                                    calendarAdapterArray[2].setCurrentYear(time[0]);
                                    calendarAdapterArray[2].setCurrentMonth(time[1]);
                                    calendarAdapterArray[2].notifyDataSetChanged();
                                }
                                break;

                            case 2:
                                if (index < lastIndex) {
                                    time = calendarAdapterArray[1].getMonthAhead();
                                    calendarAdapterArray[0].setCurrentYear(time[0]);
                                    calendarAdapterArray[0].setCurrentMonth(time[1]);
                                    calendarAdapterArray[0].notifyDataSetChanged();
                                } else {
                                    time = calendarAdapterArray[1].getMonthNext();
                                    calendarAdapterArray[2].setCurrentYear(time[0]);
                                    calendarAdapterArray[2].setCurrentMonth(time[1]);
                                    calendarAdapterArray[2].notifyDataSetChanged();
                                }
                                break;

                            case 3:
                                if (index == lastIndex) {
                                    time = calendarAdapterArray[2].getMonthAhead();
                                    calendarAdapterArray[1].setCurrentYear(time[0]);
                                    calendarAdapterArray[1].setCurrentMonth(time[1]);
                                    calendarAdapterArray[1].notifyDataSetChanged();
                                } else {
                                    time = calendarAdapterArray[2].getMonthNext();
                                    calendarAdapterArray[0].setCurrentYear(time[0]);
                                    calendarAdapterArray[0].setCurrentMonth(time[1]);
                                    calendarAdapterArray[0].notifyDataSetChanged();
                                }
                                break;

                            case 4:
                                time = calendarAdapterArray[0].getMonthNext();
                                calendarAdapterArray[1].setCurrentYear(time[0]);
                                calendarAdapterArray[1].setCurrentMonth(time[1]);
                                calendarAdapterArray[1].notifyDataSetChanged();
                                calendarPanel.setCurrentItem(1, false);
                                break;
                        }
                        lastPosition = position;
                        break;

                    case ViewPager.SCROLL_STATE_SETTLING:
                        System.out.println("SCROLL_STATE_SETTLING");
                        break;
                }
            }
        });
        calendarPanel.setCurrentItem(1, false);

        Calendar today = Calendar.getInstance();
        todayText.setText(String.valueOf(today.get(Calendar.DAY_OF_MONTH)));
        setChosenDay(today);
    }

    /**
     * 跳转到今天
     * @param view
     */
    public void jumpToToday(View view) {
        int index = calendarPanel.getCurrentItem();
        CalendarAdapter currentAdapter = null;
        int [] time;
        Calendar today = Calendar.getInstance();
        switch (index) {
            case 1:
                currentAdapter = calendarAdapterArray[0];
                time = currentAdapter.getMonthAhead();
                if (MyCalendar.isThisMonth(time[0], time[1])) {
                    calendarPanel.setCurrentItem(0, true);
                    return;
                }
                time = currentAdapter.getMonthNext();
                if (MyCalendar.isThisMonth(time[0], time[1])) {
                    calendarPanel.setCurrentItem(2, true);
                    return;
                }
                calendarAdapterArray[1].setCurrentYear(today.get(Calendar.YEAR));
                calendarAdapterArray[1].setCurrentMonth(today.get(Calendar.MONTH));
                calendarAdapterArray[1].notifyDataSetChanged();
                calendarPanel.setCurrentItem(2, true);
                resetCurrentMonth(1);
                break;

            case 2:
                currentAdapter = calendarAdapterArray[1];
                time = currentAdapter.getMonthAhead();
                if (MyCalendar.isThisMonth(time[0], time[1])) {
                    calendarPanel.setCurrentItem(1, true);
                    return;
                }
                time = currentAdapter.getMonthNext();
                if (MyCalendar.isThisMonth(time[0], time[1])) {
                    calendarPanel.setCurrentItem(3, true);
                    return;
                }
                calendarAdapterArray[2].setCurrentYear(today.get(Calendar.YEAR));
                calendarAdapterArray[2].setCurrentMonth(today.get(Calendar.MONTH));
                calendarAdapterArray[2].notifyDataSetChanged();
                calendarPanel.setCurrentItem(3, true);
                resetCurrentMonth(2);
                break;

            case 3:
                currentAdapter = calendarAdapterArray[2];
                time = currentAdapter.getMonthAhead();
                if (MyCalendar.isThisMonth(time[0], time[1])) {
                    calendarPanel.setCurrentItem(2, true);
                    return;
                }
                time = currentAdapter.getMonthNext();
                if (MyCalendar.isThisMonth(time[0], time[1])) {
                    calendarPanel.setCurrentItem(4, true);
                    return;
                }
                calendarAdapterArray[0].setCurrentYear(today.get(Calendar.YEAR));
                calendarAdapterArray[0].setCurrentMonth(today.get(Calendar.MONTH));
                calendarAdapterArray[0].notifyDataSetChanged();
                calendarPanel.setCurrentItem(4, true);
                resetCurrentMonth(0);
                break;
        }
    }

    /**
     * 添加日程
     * @param view
     */
    public void addEvent(View view) {
        Intent intent = new Intent(this, EditActivity.class);
        Event event = new Event();
        if (lastItem != null)
            event.setTime(lastItem.year, lastItem.month, lastItem.day, 9, 0);
        intent.putExtra("event", event);
        startActivityForResult(intent, REQUEST_CODE_ADD_EVENT);
    }

    /**
     * 事件点击响应
     */
    private View.OnClickListener eventClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Event event = (Event) v.getTag();
            Intent intent = new Intent(MainActivity.this, EventActivity.class);
            intent.putExtra("event", event);
            startActivityForResult(intent, REQUEST_CODE_SHOW_EVENT);
        }
    };

    /**
     * 刷新标题栏
     * @param date
     */
    public void setChosenDay(Calendar date) {
        int currentYear = date.get(Calendar.YEAR);
        int currentMonth = date.get(Calendar.MONTH);
        int currentDay = date.get(Calendar.DAY_OF_MONTH);
        monthDateTextView.setText(String.valueOf(currentMonth + 1) + "月" + currentDay + "日");
        yearTextView.setText(String.valueOf(currentYear));
        Calendar today = Calendar.getInstance();
        date.set(currentYear, currentMonth, currentDay, 0, 0, 0);
        today.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        double days = (date.getTime().getTime() - today.getTime().getTime()) * 1.0 / (24.0*60.0*60.0*1000.0);
        long diff = Math.round(days);
        if (diff == 0)
            diffTextView.setText("今天");
        else if (diff == 1)
            diffTextView.setText("明天");
        else if (diff == -1)
            diffTextView.setText("昨天");
        else if (diff > 1)
            diffTextView.setText(String.valueOf(diff) + "天后");
        else
            diffTextView.setText(String.valueOf(-diff) + "天前");
        if (MyCalendar.isThisMonth(currentYear, currentMonth))
            todayButton.setVisibility(View.INVISIBLE);
        else
            todayButton.setVisibility(View.VISIBLE);

        ArrayList<Event> events = CalendarDAO.getEventList(currentYear, currentMonth + 1, currentDay);
        if (events.size() != 0) {
            noneTextView.setVisibility(View.GONE);
            eventView.update(events, eventClickListener);
        } else {
            eventView.removeAllViews();
            noneTextView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 刷新标题栏
     * @param currentYear
     * @param currentMonth
     * @param currentDay
     */
    public void setChosenDay(int currentYear, int currentMonth, int currentDay) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(currentYear, currentMonth, currentDay);
        setChosenDay(calendar);
    }

    /**
     * 重置当月以及两侧的日历
     * @param index
     */
    private void resetCurrentMonth(int index) {
        CalendarAdapter currentAdapter = calendarAdapterArray[index];
        CalendarAdapter aheadAdapter = calendarAdapterArray[(index + 2) % 3];
        CalendarAdapter nextAdapter = calendarAdapterArray[(index + 1) % 3];
        int[] aheadMonth = currentAdapter.getMonthAhead();
        int[] nextMonth = currentAdapter.getMonthNext();
        aheadAdapter.setCurrentYear(aheadMonth[0]);
        aheadAdapter.setCurrentMonth(aheadMonth[1]);
        aheadAdapter.notifyDataSetChanged();
        nextAdapter.setCurrentYear(nextMonth[0]);
        nextAdapter.setCurrentMonth(nextMonth[1]);
        nextAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        CalendarDAO.closeDatabase();
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_ADD_EVENT:
                switch (resultCode) {
                    case EditActivity.RESULT_CODE_UPDATE:
                        calendarAdapterArray[0].notifyDataSetChanged();
                        calendarAdapterArray[1].notifyDataSetChanged();
                        calendarAdapterArray[2].notifyDataSetChanged();
                        if (lastItem == null)
                            setChosenDay(Calendar.getInstance());
                        else
                            setChosenDay(lastItem.year, lastItem.month, lastItem.day);
                        break;
                }
                break;

            case REQUEST_CODE_SHOW_EVENT:
                switch (resultCode) {
                    case EventActivity.RESULT_CODE_UPDATE:
                        calendarAdapterArray[0].notifyDataSetChanged();
                        calendarAdapterArray[1].notifyDataSetChanged();
                        calendarAdapterArray[2].notifyDataSetChanged();
                        if (lastItem == null)
                            setChosenDay(Calendar.getInstance());
                        else
                            setChosenDay(lastItem.year, lastItem.month, lastItem.day);
                        break;
                }
                break;
        }
    }
}
